package org.expressme.employee.mgmt;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Implementation of Facade.
 * 
 * @author Michael Liao (askxuefeng@gmail.com)
 */
public class FacadeImpl implements Facade {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Employee createEmployee(String name, String title, boolean gender, Date birth) {
        Employee p = new Employee();
        p.setId(UUID.randomUUID().toString().replace("-", ""));
        p.setName(name);
        p.setTitle(title);
        p.setGender(gender);
        p.setBirth(birth);
        jdbcTemplate.update(
                "insert into employee(id,name,title,gender,birth) values(?,?,?,?,?)",
                new Object[] {
                        p.getId(),
                        p.getName(),
                        p.getTitle(),
                        p.isGender(),
                        p.getBirth()
                }
        );
        return p;
    }

    public void deleteEmployee(String id) {
        jdbcTemplate.update("delete from employee where id=?", new Object[] { id });
    }

    @SuppressWarnings("unchecked")
    public List<Employee> queryByName(String name) {
        if (name==null || name.trim().length() == 0)
            throw new IllegalArgumentException("Name cannot be empty.");
        return jdbcTemplate.query(
                "select * from employee where name=? order by name, birth",
                new Object[] { name },
                new EmployeeRowMapper()
        );
    }

    @SuppressWarnings("unchecked")
    public List<Employee> queryAll() {
        return jdbcTemplate.query(
                "select * from employee order by name, birth",
                new EmployeeRowMapper()
        );
    }

}
